/**
 * 
 */
package test.mysql;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
/**
 * @author Windows 7
 *
 */

public class FileSavaAndGet {

	private final String driver="com.mysql.jdbc.Driver";//驱动
	
	private final String url="jdbc:mysql://localhost:3306/simulink";// 数据库联接
	
	public void	fileSave() {
		Connection conn=null;
		try{
			Class.forName(driver).newInstance();
			conn=DriverManager.getConnection(url,"root","admin");
			File file=new File("res/test.xml");
			FileInputStream fis=new FileInputStream(file);
			PreparedStatement pstmt=conn.prepareStatement(
				"insert into test(file) values(?)"
			);
			
			int bytes=(int)file.length();
			System.out.println(bytes);
			pstmt.setBinaryStream(1,fis,bytes);//1为插入的参数1，2。。。fileInStream为插入的数据，bytes为字节长度
			pstmt.executeUpdate();
			conn.close();
			fis.close();
		} catch(Exception e){
			System.out.println(e.getMessage());
			System.out.println("exception");
		}
	}
	
	public void	fileGet() {
		Connection conn=null;
		try{
			Class.forName(driver).newInstance();
			conn=DriverManager.getConnection(url,"root","admin");
			File file=new File("res/test_out.xml");
			FileOutputStream fos=new FileOutputStream(file);
			
			Statement statement = conn.createStatement();
			String sql = "select * from test;";
			
			ResultSet resultSet = statement.executeQuery(sql);
			resultSet.next();
			//1 method
//			byte[] buffer = resultSet.getBytes("file");
//			fos.write(buffer);
//			fos.flush();
//			fos.close();
//			conn.close();
			//2 method
			byte[] buffer = new byte[2048];
			int lenght;
			
			InputStream inputStream = resultSet.getBinaryStream("file");
			while ((lenght = inputStream.read(buffer)) != -1) {
				fos.write(buffer, 0, lenght);
			}		
			fos.flush();
			inputStream.close();
			fos.close();
			conn.close();
		} catch(Exception e){
			System.out.println(e.getMessage());
			System.out.println("exception");
		}
	}
	
	public static void main(String[] args) {
	
		new FileSavaAndGet().fileGet();
	}
}
